package com.villaday.idf.fragment;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.android.material.appbar.AppBarLayout;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.AppContext;
import com.villaday.idf.R;
import com.villaday.idf.activity.BourbonListActivity;
import com.villaday.idf.activity.ChooseCityActity;
import com.villaday.idf.activity.SearchBournActivity;
import com.villaday.idf.adapter.BournAdapter;
import com.villaday.idf.adapter.BournlistHeadAddrSortAdapter;
import com.villaday.idf.adapter.BournlistHeadCityAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseDialog;
import com.villaday.idf.base.BaseFragment;
import com.villaday.idf.base.OnAdapterCallbackListener;
import com.villaday.idf.custom.CustomPopupWindow;
import com.villaday.idf.custom.ErWeiMaDialog;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.LoadingSaveDialog;
import com.villaday.idf.custom.DividerItemDecoration.RVItemDecoration;
import com.villaday.idf.model.Cities_areasEntity;
import com.villaday.idf.model.Cities_villagesEntity;
import com.villaday.idf.model.Locations_citiesEntity;
import com.villaday.idf.model.Material_postersEntity;
import com.villaday.idf.model.Surrounds_citiesEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.ShareUtilse;
import com.villaday.idf.util.ToastUtil;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.bakumon.statuslayoutmanager.library.OnStatusChildClickListener;
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager;

import static android.app.Activity.RESULT_OK;

/**
 * 目的地
 */
public class BournFragment extends BaseFragment implements OkHttpUtil.OnDataListener, View.OnClickListener, OnAdapterCallbackListener, AbsRecyclerViewAdapter.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener, BaseDialog.OnItemClickListener {

    /*  @BindView(R.id.tab)
      TabLayout tabLayout;
      @BindView(R.id.vp)
      ViewPager vp;*/
    @BindView(R.id.tv_choseCity)
    TextView tvChoseCity;
    @BindView(R.id.rv_head_city)
    RecyclerView rvHeadCity;
    @BindView(R.id.toolbar_search)
    Toolbar toolbar_search;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;

    @BindView(R.id.rv_goods)
    RecyclerView rvGoods;
    @BindView(R.id.ll_addrSort)
    View llAddrSort;
    @BindView(R.id.tv_addr)
    TextView tvAddr;
    @BindView(R.id.tv_sort)
    TextView tvSort;
    @BindView(R.id.activity_main_app_bar)
    AppBarLayout appBarLayout;


    private Gson gson = new GsonBuilder().create();
    private int currentCityPosition = -1;//当前城市position
    private int currentAddPosition = -1;//当前区position
    private int currentSortPosition = 0;//当前区position
    private String city = "";//城市名称(如:深圳)
    private String area = "";//区县名称(如:盐田区)

    private String currentCityid = "";
    private int pageNo = 1;
    private int nextIndex = 1;
    private int pageSize = 10;
    List<Cities_villagesEntity.BodyEntity.ListEntity> data = new ArrayList();


    private List<String> titles = new ArrayList<>();
    private Locations_citiesEntity locations_citiesEntity;
    private BournlistHeadCityAdapter adapter;
    private Surrounds_citiesEntity surrounds_citiesEntity;
    private LoadingDialog loadingDialog;
    private BournAdapter bournAdapter;

    private String areaId = "";
    private int sort = 0;
    private BournlistHeadAddrSortAdapter bournlistHeadAddrSortAdapter;
    private Cities_areasEntity cities_areasEntity;
    private List<Cities_areasEntity.BodyEntity> qudatas = new ArrayList<>();
    private List<Cities_areasEntity.BodyEntity> dataSort;
    private TagAdapter<Surrounds_citiesEntity.BodyEntity> tagAdapter;
    private String currentCityidCurrent = "";//city name临时变量
    private String cityCurrent = "";
    private StatusLayoutManager statusLayoutManager;


    public BournFragment() {
        // Required empty public constructor
    }


    public static BournFragment instance() {
        BournFragment bournFragment = new BournFragment();
        return bournFragment;
    }

    public void setCity() {


        if (!TextUtils.isEmpty(AppContext.cityCurrent) && !AppContext.cityCurrent.equals(cityCurrent)) {
            currentCityidCurrent = AppContext.currentCityidCurrent;
            cityCurrent = AppContext.cityCurrent;
            currentCityid = currentCityidCurrent;
            city = cityCurrent;

            tvAddr.setText("位置区域");

            areaId = "";
            area = "";

            currentAddPosition = -1;
            Map<String, String> map = new HashMap<>();
            map.put("type", "0");
            OkHttpUtil.getJSON(getContext(), String.format(Constant.URL.surrounds_cities, currentCityidCurrent), map, this);

            currentCityPosition = -1;

            loadingDialog = LoadingDialog.newInstance("加载中");
            loadingDialog.show(getActivity().getFragmentManager(), "loading");
            onRefresh();
            tvChoseCity.setText(AppContext.cityCurrent);
        } else {

        }


    }

    @Override
    protected int getViewResId() {
        return R.layout.fragment_bourn;
    }

    @Override
    protected void init(View v) {

        statusLayoutManager = setupDefaultStatusLayoutManager(srl, new OnStatusChildClickListener() {
            @Override
            public void onEmptyChildClick(View view) {

            }

            @Override
            public void onErrorChildClick(View view) {
                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getActivity().getFragmentManager(), "loading");

                getCity();
            }

            @Override
            public void onCustomerChildClick(View view) {

            }
        });
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset >= 0) {
                    srl.setEnabled(true);
                } else {
                    srl.setEnabled(false);
                }
            }
        });
        dataSort = new ArrayList<>();
        dataSort.add(new Cities_areasEntity.BodyEntity("默认排序", 0));
        dataSort.add(new Cities_areasEntity.BodyEntity("人气最高", 3));
        loadingDialog = LoadingDialog.newInstance("加载中");
        loadingDialog.show(getActivity().getFragmentManager(), "loading");
        srl.setOnRefreshListener(this);
        getCity();
        adapter = new BournlistHeadCityAdapter(getContext());
        rvHeadCity.addItemDecoration(new RVItemDecoration(LinearLayout.HORIZONTAL, PhoneUtil.dp2px(getContext(), 5), getResources().getColor(R.color.colorWhite), PhoneUtil.dp2px(getContext(), 1)));
        adapter.setFullScreen(true);
        rvHeadCity.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        rvHeadCity.setAdapter(adapter);
        adapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                tvAddr.setText("位置区域");

                areaId = "";
                area = "";

                currentAddPosition = -1;


                if (surrounds_citiesEntity != null && surrounds_citiesEntity.getBody() != null) {
                    surrounds_citiesEntity.getBody().get(position).setCheck(!surrounds_citiesEntity.getBody().get(position).isCheck());
                    if (currentCityPosition != -1 && currentCityPosition != position) {
                        surrounds_citiesEntity.getBody().get(currentCityPosition).setCheck(!surrounds_citiesEntity.getBody().get(currentCityPosition).isCheck());

                    }
                    if (surrounds_citiesEntity.getBody().get(position).isCheck()) {
                        currentCityid = surrounds_citiesEntity.getBody().get(position).getId();
                        city = surrounds_citiesEntity.getBody().get(position).getName();

                        currentCityPosition = position;

                    } else {
                        currentCityid = currentCityidCurrent;
                        city = cityCurrent;
                        AppContext.currentCityidCurrent = currentCityidCurrent;//当前城市id
                        AppContext.cityCurrent = cityCurrent;//当前城市
                        currentCityPosition = -1;

                    }
                    adapter.notifyDataSetChanged();
                    loadingDialog = LoadingDialog.newInstance("加载中");
                    loadingDialog.show(getActivity().getFragmentManager(), "loading");
                    onRefresh();
                }
            }
        });

        rvGoods.setLayoutManager(new LinearLayoutManager(getContext()));
        bournAdapter = new BournAdapter(getContext(), this, this);
        rvGoods.setAdapter(bournAdapter);

        rvGoods.addItemDecoration(new RVItemDecoration(LinearLayout.VERTICAL, PhoneUtil.dp2px(getContext(), 1), getResources().getColor(R.color.primaryBg), PhoneUtil.dp2px(getContext(), 1)));
        bournAdapter.setOnItemClickListener(this);
       /* View inflate = View.inflate(getContext(), R.layout.recycle_head, null);
        homeListSaleAdapter.addHeaderView(inflate);*/
        bournAdapter.setEmptyView(R.layout.empty_tips);
        bournAdapter.setEmptyTips(R.id.tv_emptyTips, "没有更多了");
        tvChoseCity.setText(AppContext.cityCurrent);


    }


    @OnClick({R.id.tv_choseCity, R.id.ll_fstoresearch, R.id.tv_addr, R.id.tv_sort})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_choseCity: {//搜索城市
                if (locations_citiesEntity != null && locations_citiesEntity.getBody() != null) {
                    Intent intent = new Intent(getContext(), ChooseCityActity.class);
                    intent.putExtra("cityId", currentCityidCurrent);
                    intent.putExtra("type", "0");
                    startActivityForResult(intent, 123);
                }

            }
            break;
            case R.id.ll_fstoresearch: {//搜索目的地
                Intent intent = new Intent(getContext(), SearchBournActivity.class);
                intent.putExtra("cityId", currentCityidCurrent);
                startActivityForResult(intent, 124);
            }
            break;
            case R.id.tv_addr: {//位置区域
/*
                currentAddPosition = -1;
*/
                tvAddr.setSelected(true);
                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getActivity().getFragmentManager(), "loading");
                OkHttpUtil.getJSON(getContext(), String.format(Constant.URL.cities_areas, currentCityid), this);


                CustomPopupWindow.Builder builder = new CustomPopupWindow.Builder();
                final CustomPopupWindow builder1 = builder.setheight(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                        .setwidth(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                        .setOutSideCancel(true)
                        .setContext(getContext())
                        .setContentView(R.layout.popu_bourn_head_chose_addr_sort)
                        .setOnDismissListener(new PopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                                tvAddr.setSelected(false);
                            }
                        })
                        .builder();

                builder1.getItemView(R.id.close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        builder1.dismiss();
                    }
                });
                RecyclerView rvAddr = (RecyclerView) builder1.getItemView(R.id.rv_addr_sort);
                rvAddr.setLayoutManager(new LinearLayoutManager(getContext()));
                bournlistHeadAddrSortAdapter = new BournlistHeadAddrSortAdapter(getContext());
                rvAddr.setAdapter(bournlistHeadAddrSortAdapter);

                rvAddr.addItemDecoration(new RVItemDecoration(LinearLayout.VERTICAL, PhoneUtil.dp2px(getContext(), 1), getResources().getColor(R.color.colorBg), PhoneUtil.dp2px(getContext(), 1)));
                bournlistHeadAddrSortAdapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View v, int position) {
                        builder1.dismiss();
                        if (true) {
                            qudatas.get(position).setCheck(!qudatas.get(position).isCheck());


                            if (currentAddPosition != -1 && currentAddPosition != position) {
                                qudatas.get(currentAddPosition).setCheck(!qudatas.get(currentAddPosition).isCheck());

                            }
                            if (qudatas.get(position).isCheck()) {
                                areaId = qudatas.get(position).getId();
                                area = qudatas.get(position).getName();
                                currentAddPosition = position;

                                tvAddr.setText(qudatas.get(position).getName());

                            } else {
                                tvAddr.setText("位置区域");

                                areaId = "";
                                area = "";
                                currentAddPosition = -1;

                            }
                            bournlistHeadAddrSortAdapter.notifyDataSetChanged();
                            loadingDialog = LoadingDialog.newInstance("加载中");
                            loadingDialog.show(getActivity().getFragmentManager(), "loading");
                            onRefresh();
                        }

                    }
                });
       /* View inflate = View.inflate(getContext(), R.layout.recycle_head, null);
        homeListSaleAdapter.addHeaderView(inflate);*/
                bournlistHeadAddrSortAdapter.setEmptyView(R.layout.empty_tips);
                bournlistHeadAddrSortAdapter.setEmptyTips(R.id.tv_emptyTips, "没有更多了");


                builder1.showAsLaction(llAddrSort, Gravity.BOTTOM, 0, 0);

            }
            break;
            case R.id.tv_sort: {//默认排序
                tvSort.setSelected(true);
                if (currentSortPosition == 0) {
                    dataSort.get(0).setCheck(true);
                    dataSort.get(1).setCheck(false);


                    sort = 0;
                    tvSort.setText("默认排序");
                } else {
                    dataSort.get(0).setCheck(false);
                    dataSort.get(1).setCheck(true);
                    tvSort.setText("人气最高");
                    sort = 3;
                }

                CustomPopupWindow.Builder builder = new CustomPopupWindow.Builder();
                final CustomPopupWindow builder1 = builder.setheight(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                        .setwidth(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                        .setOutSideCancel(true)
                        .setContext(getContext())
                        .setContentView(R.layout.popu_bourn_head_chose_addr_sort)
                        .setOnDismissListener(new PopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                                tvSort.setSelected(false);
                            }
                        })
                        .builder();

                builder1.getItemView(R.id.close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        builder1.dismiss();
                    }
                });


                final RecyclerView rvAddr = (RecyclerView) builder1.getItemView(R.id.rv_addr_sort);
                rvAddr.setLayoutManager(new LinearLayoutManager(getContext()));
                final BournlistHeadAddrSortAdapter bournlistHeadSortAdapter = new BournlistHeadAddrSortAdapter(getContext());
                rvAddr.setAdapter(bournlistHeadSortAdapter);

                rvAddr.addItemDecoration(new RVItemDecoration(LinearLayout.VERTICAL, PhoneUtil.dp2px(getContext(), 1), getResources().getColor(R.color.colorBg), PhoneUtil.dp2px(getContext(), 1)));
                bournlistHeadSortAdapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View v, int position) {
                        builder1.dismiss();
                        if (position == 0) {
                            dataSort.get(0).setCheck(true);
                            dataSort.get(1).setCheck(false);


                            sort = 0;
                            tvSort.setText("默认排序");
                        } else {
                            dataSort.get(0).setCheck(false);
                            dataSort.get(1).setCheck(true);
                            tvSort.setText("人气最高");
                            sort = 3;
                        }
                        currentSortPosition = position;
                        bournlistHeadSortAdapter.notifyDataSetChanged();
                        loadingDialog = LoadingDialog.newInstance("加载中");
                        loadingDialog.show(getActivity().getFragmentManager(), "loading");
                        onRefresh();
                    }
                });
       /* View inflate = View.inflate(getContext(), R.layout.recycle_head, null);
        homeListSaleAdapter.addHeaderView(inflate);*/
                bournlistHeadSortAdapter.setEmptyView(R.layout.empty_tips);
                bournlistHeadSortAdapter.setEmptyTips(R.id.tv_emptyTips, "没有更多了");


                builder1.showAsLaction(llAddrSort, Gravity.BOTTOM, 0, 0);
                bournlistHeadSortAdapter.setData(dataSort);
            }
            break;

        }

    }


    @OnClick(R.id.img)
    public void onViewClicked() {
        CustomPopupWindow.Builder builder = new CustomPopupWindow.Builder();
        final CustomPopupWindow builder1 = builder.setheight(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                .setwidth(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                .setOutSideCancel(true)
                .setContext(getContext())
                .setContentView(R.layout.popu_bourn_head_chosecity)
                .builder();
        final TagFlowLayout idFlowlayout = (TagFlowLayout) builder1.getItemView(R.id.id_flowlayout);

        builder1.getItemView(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder1.dismiss();
            }
        });
        builder1.getItemView(R.id.tv_reset).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentCityPosition != -1) {
                    tvAddr.setText("位置区域");

                    areaId = "";
                    area = "";
                    currentCityid = currentCityidCurrent;
                    city = cityCurrent;
                    AppContext.currentCityidCurrent = currentCityidCurrent;//当前城市id
                    AppContext.cityCurrent = cityCurrent;//当前城市

                    currentAddPosition = -1;

                    surrounds_citiesEntity.getBody().get(currentCityPosition).setCheck(false);
                    rvHeadCity.scrollToPosition(0);
                    adapter.notifyDataSetChanged();
                    tagAdapter.notifyDataChanged();

                    currentCityPosition = -1;

                    builder1.dismiss();
                    loadingDialog = LoadingDialog.newInstance("加载中");
                    loadingDialog.show(getActivity().getFragmentManager(), "loading");
                    onRefresh();
                }


            }
        });


        builder1.showAsLaction(toolbar_search, Gravity.BOTTOM, 0, 0);
        if (surrounds_citiesEntity != null && surrounds_citiesEntity.getBody() != null) {
            tagAdapter = new TagAdapter<Surrounds_citiesEntity.BodyEntity>(surrounds_citiesEntity.getBody()) {
                @Override
                public View getView(FlowLayout parent, int position, Surrounds_citiesEntity.BodyEntity s) {
                    TextView tv = (TextView) getActivity().getLayoutInflater().inflate(R.layout.tv,
                            idFlowlayout, false);
                    tv.setText(s.getName());

                    return tv;
                }
            };
            idFlowlayout.setAdapter(tagAdapter);
            if (currentCityPosition != -1) {
                tagAdapter.setSelectedList(currentCityPosition);
            }

            idFlowlayout.getSelectedList();
            idFlowlayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
                @Override
                public boolean onTagClick(View view, int position, FlowLayout parent) {
                    builder1.dismiss();
                    tvAddr.setText("位置区域");

                    areaId = "";
                    area = "";

                    currentAddPosition = -1;
                    if (surrounds_citiesEntity != null && surrounds_citiesEntity.getBody() != null) {
                        surrounds_citiesEntity.getBody().get(position).setCheck(!surrounds_citiesEntity.getBody().get(position).isCheck());
                        if (currentCityPosition != -1 && currentCityPosition != position) {
                            surrounds_citiesEntity.getBody().get(currentCityPosition).setCheck(!surrounds_citiesEntity.getBody().get(currentCityPosition).isCheck());

                        }
                        if (surrounds_citiesEntity.getBody().get(position).isCheck()) {
                            currentCityid = surrounds_citiesEntity.getBody().get(position).getId();
                            city = surrounds_citiesEntity.getBody().get(position).getName();

                            currentCityPosition = position;

                        } else {
                            currentCityid = locations_citiesEntity.getBody().getId();
                            city = locations_citiesEntity.getBody().getName();

                            currentCityPosition = -1;

                        }
                        rvHeadCity.scrollToPosition(position);

                        adapter.notifyDataSetChanged();
                        loadingDialog = LoadingDialog.newInstance("加载中");
                        loadingDialog.show(getActivity().getFragmentManager(), "loading");
                        onRefresh();

                    }
                    return true;
                }
            });
        }
    }

    public void getCity() {
        OkHttpUtil.getJSON(getContext(), Constant.URL.locations_cities, this);

    }

    @Override
    public void onResponse(String url, String json) {
        if (statusLayoutManager != null) {

            statusLayoutManager.showSuccessLayout();
        }
        if (Constant.URL.locations_cities.equals(url)) {
            LogeUtil.e("locations_cities", json);
            locations_citiesEntity = gson.fromJson(json, Locations_citiesEntity.class);
            if ("200".equals(locations_citiesEntity.getCode()) && locations_citiesEntity.getBody() != null) {
                Map<String, String> map = new HashMap<>();
                map.put("type", "0");
                OkHttpUtil.getJSON(getContext(), String.format(Constant.URL.surrounds_cities, locations_citiesEntity.getBody().getId()),map, this);

                if (!TextUtils.isEmpty(AppContext.currentCityidCurrent)) {
                    currentCityidCurrent = AppContext.currentCityidCurrent;
                    cityCurrent = AppContext.cityCurrent;
                } else {
                    currentCityidCurrent = locations_citiesEntity.getBody().getId();
                    cityCurrent = locations_citiesEntity.getBody().getName();
                    AppContext.currentCityidCurrent = currentCityidCurrent;//当前城市id
                    AppContext.cityCurrent = cityCurrent;//当前城市
                }
                currentCityid = currentCityidCurrent;
                city = cityCurrent;
                getCityList(currentCityid, AppContext.currentCityidCurrent, sort);

            }
        } else if (String.format(Constant.URL.surrounds_cities, currentCityid).equals(url)) {
            LogeUtil.e("surrounds_cities", json);
            surrounds_citiesEntity = gson.fromJson(json, Surrounds_citiesEntity.class);
            if ("200".equals(surrounds_citiesEntity.getCode()) && surrounds_citiesEntity.getBody() != null) {
                adapter.setData(surrounds_citiesEntity.getBody());

            }


        } else if (String.format(Constant.URL.cities_areas, currentCityid).equals(url)) {
            dismissLoading();
            LogeUtil.e("cities_areas", json);
            cities_areasEntity = gson.fromJson(json, Cities_areasEntity.class);
            if ("200".equals(cities_areasEntity.getCode()) && cities_areasEntity.getBody() != null) {
                qudatas.clear();
                qudatas.add(new Cities_areasEntity.BodyEntity("全部", ""));
                qudatas.addAll(cities_areasEntity.getBody());
                if (currentAddPosition != -1) {
                    qudatas.get(currentAddPosition).setCheck(true);

                }
                bournlistHeadAddrSortAdapter.setData(qudatas);

            }

        } else if (Constant.URL.cities_villages.substring(0, 31).equals(url.substring(0, 31))) {
            dismissLoading();
            LogeUtil.e("cities_villages", json);
            Cities_villagesEntity cities_villagesEntity = gson.fromJson(json, Cities_villagesEntity.class);
            removeLoadingItem();
            if (pageNo == 1) {
                data.clear();
            }

            if ("200".equals(cities_villagesEntity.getCode())) {
                data.addAll(cities_villagesEntity.getBody().getList());
                if (cities_villagesEntity.getBody().isHasNext()) {
                    data.add(new Cities_villagesEntity.BodyEntity.ListEntity(1));
                    nextIndex = pageNo + 1;

                } else {
                    addBaseLine();
                }

            } else {
                addBaseLine();
            }
            bournAdapter.setData(data);
        }
    }


    @Override
    public void onFailure(String url, String error) {
        dismissLoading();
        if (statusLayoutManager != null) {

            statusLayoutManager.showErrorLayout();
        }
        ToastUtil.initToast(getContext(), "网络错误");
    }

    //获取目的地列表
    private void getCityList(String cityId, String areaId, int sort) {
        Map<String, String> map = new HashMap<>();
        map.put("pageNo", pageNo + "");
        map.put("pageSize", pageSize + "");
        map.put("areaId", areaId);
        map.put("sort", sort + "");


        OkHttpUtil.getJSON(getContext(), String.format(Constant.URL.cities_villages, cityId), map, this);

    }

    private void removeLoadingItem() {
        if (data.size() > 0) {
            if (data.get(data.size() - 1).getType() == 1) {
                data.remove(data.size() - 1);
            }
        }
    }

    private void addBaseLine() {
        if (pageNo != 1) {
            data.add(new Cities_villagesEntity.BodyEntity.ListEntity(2));
        }
    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        if (srl != null && srl.isRefreshing()) {
            srl.setRefreshing(false);
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_tuiguang://推荐

                loadingDialog = LoadingDialog.newInstance("跳转中");
                loadingDialog.show(getActivity().getFragmentManager(), "loading");
                String villageId = data.get((Integer) view.getTag()).getId();

                OkHttpUtil.getJSON(getContext(), String.format(Constant.URL.vips_villages_posters, villageId), new OkHttpUtil.OnDataListener() {
                    @Override
                    public void onResponse(String url, String json) {
                        if (!TextUtils.isEmpty(json)) {
                            dismissLoading();
                            Material_postersEntity material_postersEntity = gson.fromJson(json, Material_postersEntity.class);
                            if ("200".equals(material_postersEntity.getCode())) {
                                LogeUtil.e("vips_villages_posters" + json);
                                ErWeiMaDialog erWeiMaDialog = ErWeiMaDialog.newInstance(material_postersEntity.getBody().getPosterList().get(0).getUrl());
                                erWeiMaDialog.show(getActivity().getFragmentManager());

                                erWeiMaDialog.setOnItemClickListener(BournFragment.this);
                            } else {
                                ToastUtil.initToast(getContext(), material_postersEntity.getMsg());
                            }
                        }

                    }

                    @Override
                    public void onFailure(String url, String error) {

                    }
                });

                break;

        }


    }

    @Override
    public void onCallback() {
        if (nextIndex == pageNo + 1) {
            pageNo++;
            getCityList(currentCityid, areaId, sort);
        }
    }

    @Override
    public void onItemClick(View v, int position) {
        Intent intent = new Intent(getContext(), BourbonListActivity.class);
        intent.putExtra("villageId", data.get(position).getId());
        intent.putExtra("city", city);
        intent.putExtra("area", area);

        startActivity(intent);
    }

    @Override
    public void onRefresh() {
        pageNo = 1;
        nextIndex = 1;
        getCityList(currentCityid, areaId, sort);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 123) {//城市搜索

                currentCityidCurrent = data.getStringExtra("cityId");
                cityCurrent = data.getStringExtra("cityName");
                tvChoseCity.setText(cityCurrent);

                tvAddr.setText("位置区域");

                areaId = "";
                area = "";
                currentCityid = currentCityidCurrent;
                city = cityCurrent;
                AppContext.currentCityidCurrent = currentCityidCurrent;//当前城市id
                AppContext.cityCurrent = cityCurrent;//当前城市
                currentAddPosition = -1;
                Map<String, String> map = new HashMap<>();
                map.put("type", "0");
                OkHttpUtil.getJSON(getContext(), String.format(Constant.URL.surrounds_cities, currentCityidCurrent),map, this);

                adapter.notifyDataSetChanged();
                if (tagAdapter != null) {
                    tagAdapter.notifyDataChanged();

                }

                currentCityPosition = -1;

                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getActivity().getFragmentManager(), "loading");
                onRefresh();
            }
        }
    }

    @Override
    public void onItemClick(final View v) {
        switch (v.getId()) {

            case R.id.tv_wx: {
               /* loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getActivity().getFragmentManager(), "loading");
               */
                List<String> images = new ArrayList<>();
                images.add((String) v.getTag());
                ShareUtilse.shareImage(getContext(), 0, images, images.get(images.size() - 1),"");
            }
            break;
            case R.id.tv_pyq: {
               /* loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getActivity().getFragmentManager(), "loading");
                */
                List<String> images = new ArrayList<>();
                images.add((String) v.getTag());
                ShareUtilse.shareImage(getContext(), 1, images, images.get(images.size() - 1),"");
            }
            break;
            case R.id.tv_save: {
                List<String> picList = new ArrayList<>();
                picList.add((String) v.getTag());
                LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("已保存" + (1) + "/" + picList.size() + "张");
                loadingDialog.show(getActivity().getFragmentManager(), "0");
                saveImageForRecursive(picList, picList.size(), loadingDialog);


            }
            break;
        }
    }


    public void saveImageForRecursive(final List<String> img, final int imgSize, final LoadingSaveDialog loadingSaveDialog) {//递归保存
        if (loadingSaveDialog != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    loadingSaveDialog.setLoadingTips("已保存" + (imgSize - img.size() + 1) + "/" + imgSize + "张");
                }
            });

        }
        if (img.size() != 0) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    saveImageToSdCard(getContext(), img.get(0), true);

                    img.remove(0);
                    saveImageForRecursive(img, imgSize, loadingSaveDialog);
                }
            }
            ).start();
        } else {

            if (loadingSaveDialog != null) {

                loadingSaveDialog.dismiss();
            }
            Looper.prepare();
            String fileName;
            if (Build.BRAND.equals("Xiaomi")) { // 小米手机
                fileName = "/DCIM/Camera/";
            } else {  // Meizu 、Oppo
                fileName = "/DCIM/Camera/";
            }
            ToastUtil.initToast(getContext(), "图片已保存至" + fileName);
            Looper.loop();
        }

    }


    //根据网络图片url路径保存到本地
    public static final File saveImageToSdCard(Context context, String image, boolean isxiangce) {
        boolean success = false;
        File file = null;
        try {
            if (isxiangce) {
                file = createXiangCeImageFile(context);
            } else {
                file = createStableImageFile(context);

            }

            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            int code = conn.getResponseCode();

            if (code == 200) {
                is = conn.getInputStream(); // 得到网络返回的输入流
            } else {
                is = conn.getErrorStream(); // 得到网络返回的输入流
            }
            bitmap = BitmapFactory.decodeStream(is);

            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
            //MediaStore.Images.Media.insertImage(context.getContentResolver(), image, file.getName(), "你对图片的描述");

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (success) {
            return file;
        } else {
            return null;
        }
    }

    public static String IMAGE_NAME = "iv_share_";
    public static int i = 0;

    //创建相册
    public static File createXiangCeImageFile(Context context) throws IOException {
        String imageFileName = IMAGE_NAME + System.currentTimeMillis() + ".jpg";

        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        } else {  // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        }
        file = new File(fileName);

        if (file.exists()) {
            file.delete();
        }
        return file;
    }

    //创建本地保存路径
    public static File createStableImageFile(Context context) throws IOException {

        i++;
        String imageFileName = IMAGE_NAME + System.currentTimeMillis() + ".jpg";
        File storageDir = context.getExternalCacheDir();
        File image = new File(storageDir, imageFileName);
        return image;
    }
}
